package com.caiwangdai.app.ui.borrow

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Message
import com.caiwangdai.app.Const
import com.caiwangdai.app.R
import com.caiwangdai.app.backend.RetrofitHome
import com.caiwangdai.app.backend.observer.OnDataV2Listener
import com.caiwangdai.app.backend.rx.RxSchedulers
import com.caiwangdai.app.bean.PayInfoB
import com.caiwangdai.app.bean.RepayOrderDetailB
import com.caiwangdai.app.bean.SignResultB
import com.caiwangdai.app.bean.base.BaseB
import com.caiwangdai.app.bean.base.NormalResponseB
import com.caiwangdai.app.extension.*
import com.caiwangdai.app.origin.BaseActivity
import com.caiwangdai.app.origin.ToolBarManager
import com.caiwangdai.app.pay.MobileSecurePayer
import com.caiwangdai.app.ui.verify.VerifyResultActivity
import com.google.gson.Gson
import com.orhanobut.logger.Logger
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_repay_order_detail.*

//还款订单详情
class RepayOrderDetailActivity : BaseActivity() {
    override fun getLayoutResID() = R.layout.activity_repay_order_detail

    companion object {
        val ORDER_ID = "order_id"
        fun newInstance(context: Context, orderID: String): Intent {
            val intent = Intent(context, RepayOrderDetailActivity::class.java)
            intent.putExtra(ORDER_ID, orderID)
            return intent
        }
    }

    var orderID: String? = null
    var feeDetail: RepayOrderDetailB? = null

    override fun initData() {
        orderID = intent.getStringExtra(ORDER_ID)
        getUserRepaymentInfo(orderID!!)
    }

    fun getUserRepaymentInfo(orderId: String) {

        RetrofitHome.getHomeApi()
                .getUserRepaymentInfo(orderId)
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<RepayOrderDetailB>(this, swipe_refresh, true) {

                    override fun onSuccess(value: NormalResponseB<RepayOrderDetailB>) {
                        feeDetail = value.data!!
                        val obj = value.data?.info
                        obj?.apply {
                            tv_money.text = "￥${repayment_money}"
                            tv_money.setPartTextSize(0, 1, 20)
                            tv_date_loan.text = loan_date?.string2Date("yyyy-MM-dd")?.date2String("yyyy年MM月dd日")
                            tv_date_repay.text = repay_date?.string2Date("yyyy-MM-dd")?.date2String("yyyy年MM月dd日")
                        }

                    }
                })
    }

    override fun initView() {
        //toolBar
        ToolBarManager.with(this, WMContent)
                .setTitle("订单详情")
                .setNavigationIcon(R.drawable.ic_nav_arrow_white)
        //dialog
        iv_wonder.setOnClickListenerPro {
            showOrderFeeDialog(feeDetail!!)
        }

        //click
        btn_submit.setOnClickListenerPro {
            //无此权限，支付时候，有几率会出现crash现象
            RxPermissions(this)
                    .request(Manifest.permission.READ_PHONE_STATE)
                    .subscribe { granted ->
                        if (granted!!)
                            getPayInfo(orderID!!)
                        else
                            showMissingPermissionDialog("没有此权限，APP将无法正常支付!")

                    }

        }

    }


    //获取支付信息
    private fun getPayInfo(orderId: String) {
        RetrofitHome.getHomeApi()
                .getPayInfo(orderId)
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<PayInfoB>(this) {
                    override fun isShowProgressBar() = false
                    override fun onSuccess(value: NormalResponseB<PayInfoB>) {
                        super.onSuccess(value)
                        val content = value.data?.repayment_info?.toJson()
                        Logger.json(content)

                        //pay
                        val msp = MobileSecurePayer()
                        msp.payRepayment(content, MyHandler(), Const.RQF_PAY, this@RepayOrderDetailActivity, false)
                    }

                })
    }


    inner class MyHandler : Handler() {

        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val strRet = msg?.obj as String
            val result = Gson().fromJson(strRet, SignResultB::class.java)

            val retCode = result.ret_code
            val retMsg = result.ret_msg
            val resultPay = result.result_pay

            when (msg.what) {
                Const.RQF_PAY -> {
                    when (retCode) {
                        Const.RET_CODE_SUCCESS -> {
                            //  卡前置模式返回的银行卡绑定协议号，用来下次支付时使用，此处仅作为示例使用。正式接入时去掉
                            startActivity(VerifyResultActivity.newInstance(mContext, true, "还款成功"))
                        }
                        Const.RET_CODE_PROCESS -> {
                            //  处理中，掉单的情形
                            if (Const.RESULT_PAY_PROCESSING == resultPay) {
                                Logger.e("操作失败，请重试")
                            }
                        }
                        else -> {
                            //  失败
                            toast("操作失败，请重试")
                        }
                    }
                }
            }
        }
    }

    @Deprecated("弃用")
    fun actionRepay(orderId: String) {
        RetrofitHome.getHomeApi()
                .actionRepay(orderId)
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<BaseB>(this) {
                    override fun getProgressBarContent() = "还款中..."
                    override fun onSuccess(value: NormalResponseB<BaseB>) {
                        startActivity(VerifyResultActivity.newInstance(mContext, true, "还款成功"))
                    }
                })
    }

}
